#!/bin/bash

# Script intended to be executed from ncmpcpp (execute_on_song_change
# preference) running from urxvt to set album cover as background image

MPD_CONF=~/.config/mpd/mpd.conf
MUSIC_DIR=$( cat "$MPD_CONF" | grep -v '#' | grep 'music_directory' | cut -d ' ' -f2 | awk '{print $2}' | sed 's/"//g' )
DARKEN=70

TMP=/tmp
COVER=/tmp/cover.jpg
IMG_REG=".*/.*\(Front\|front\|Cover\|cover\|Art\|art\|Folder\|folder\).*[.]\(jpe?g\|png\|gif\|bmp\)"

function reset_background
{
    # is there any better way?
    printf "\e]20;;100x100+1000+1000\a"
}

{
    album="$(mpc --format %album% current)"
    artist="$(mpc --format %artist% current)"
    file="$(mpc --format %file% current)"
    dir="$MUSIC_DIR/$artist/$album"
    if [[ -d "$dir" ]] ; then
        album_dir="$dir"
    else
        album_dir="$MUSIC_DIR/${file%/*}"
    fi

    [[ -z "$album_dir" ]] && exit 1

    covers="$(find "$album_dir/" -type d -exec find {} -maxdepth 1 -type f -regex "$IMG_REG" \; )"
    src="$(echo -n "$covers" | head -n1)"
    darkenimg="$TMP/darken.jpg"
    rm -f "$COVER" "$darkenimg"
    if [[ -n "$src" ]] ; then
        light="$((100 - $DARKEN))"
        convert "$src" -fill "gray${light}" +level ${light}%,${light}% \
            +matte "$darkenimg"
        composite "$darkenimg" -compose Multiply "$src" "$COVER"
        if [[ -f "$COVER" ]] ; then
            printf "\e]20;${COVER};100x100+50+50:op=keep-aspect\a"
        else
            reset_background
        fi
    else
        reset_background
    fi
} &
